package net.sxnic.ugr.user.action;

/**
 * 
 * Introduction：用户新增action类
 * 
 * @author 孙宇飞 create date : 2010-5-16
 * @author 吕盛槐 update date : 2011-9-26
 */
import java.util.HashSet;

import net.sxnic.ugr.UgrActionSupport;
import net.sxnic.ugr.UgrConstant;
import net.sxnic.ugr.dept.DeptManager;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.role.util.RoleUtils;
import net.sxnic.ugr.user.User;
import net.sxnic.ugr.user.UserManager;
import net.sxnic.util.MvcUtils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping(value = "/admin/ugr/")
public class Create extends UgrActionSupport {

	private static Logger logger = LoggerFactory.getLogger(Create.class);
	
	private static String INPUT = "/admin/ugr/user/create";

	private User user;

	@Autowired
	private UserManager userManager;

	@Autowired
	private DeptManager deptManager;

	private String confirmPassword;

	private String confirmsignPwd;

	private String rolesHtml;

	/**
	 * 部门
	 */
	private String dept;

	/**
	 * 角色
	 */
	private String role;

	@RequestMapping(value = "/user_create.jspa", method = RequestMethod.POST)
	public String execute(String id, String dept, String role,String confirmPassword,
			RedirectAttributes model) throws Exception {

		try {
			checkRoles(Role.SYSTEM_ADMIN);
			
			//从页面取user数据
			user = new User();
			user = (User) MvcUtils.getEntityFromRequest(request, "user.", user);

			User u = userManager.getUserByUsername(user.getUsername());

			// 为了返回INPUT回显role列表

			if (u != null && StringUtils.isNotBlank(u.getUsername())) {
				rolesHtml = RoleUtils.createCheckboxHtml(new HashSet<Role>(),
						authorizationManager.getRoles(), "role");
				model.addFlashAttribute("actError","此用户名已存在。");
				return INPUT;
			}

			if (!user.getPassword().equals(confirmPassword)) {
				rolesHtml = RoleUtils.createCheckboxHtml(new HashSet<Role>(),
						authorizationManager.getRoles(), "role");
				model.addFlashAttribute("actError","登录密码和确认登录密码不匹配！请重新输入。");
				return "";
			}

			user.setPassword(DigestUtils.md5Hex(user.getPassword()));

			String tempCodes = "";

			// 部门
			// if (StringUtils.isBlank(user.getDeptCodes())) {
			// user.getDepts().clear();
			// tempCodes = "";
			// } else {
			//
			// Dept deptment = null;
			// deptment = deptManager.findByCode(user.getDeptCodes());
			//
			// user.getDepts().clear();
			// user.getDepts().add(deptment);
			//
			// }

			// 角色
			if (StringUtils.isBlank(role)) {
				user.getRoles().clear();
				tempCodes = "";
			} else {
				tempCodes = "";
				String[] roles = StringUtils.split(role, ",");
				user.getRoles().clear();
				Role r = null;
				for (String rr : roles) {
					r = authorizationManager.getRole(rr.trim());
					logger.debug("role id :" + r.getId() + " , user id :"
							+ user.getId());

					user.getRoles().add(r);

					tempCodes = tempCodes + r.getName() + ",";
				}
				// user.setRoleCodes(StringUtils.removeEnd(tempCodes, ","));
			}
			
			userManager.save(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			// 用户已存在
			model.addAttribute("actError", "保存失败");
			return INPUT;
		}

		// 重建userMap
		UgrConstant.USER_MAP = userManager.findUserMap();

		model.addFlashAttribute("msg", "createSuccess");

		return "redirect:user_browse.jspa";
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the confirmPassword
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	/**
	 * @param confirmPassword
	 *            the confirmPassword to set
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public String getRolesHtml() {
		return rolesHtml;
	}

	public void setRolesHtml(String rolesHtml) {
		this.rolesHtml = rolesHtml;
	}

	public String getDept() {
		return dept;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getConfirmsignPwd() {
		return confirmsignPwd;
	}

	public void setConfirmsignPwd(String confirmsignPwd) {
		this.confirmsignPwd = confirmsignPwd;
	}

}
